package com.skb.web.validator;

import com.skb.core.model.controller.UserModel;
import com.skb.core.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

@Repository
public class UserValidator implements Validator {

    @Autowired
    private IUserService userService;

    @Override
    public boolean supports(Class<?> aClass) {
        return UserModel.class.isAssignableFrom(aClass);
    }

    @Override
    public void validate(Object o, Errors errors) {
        UserModel userModel = (UserModel) o;

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login",
                "required.login", "Pole 'Login' jest wymagane.");


        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roles",
                "required.roles", "Pole 'Role' jest wymagane.");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName",
                "required.re-password", "Pole 'Imie' jest wymagane");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
                "required.departments", "Pole 'Nazwisko' jest wymagane.");
//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
//                "required.departments", "Pole 'Nazwisko' jest wymagane.");
//        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName",
//                "required.departments", "Pole 'Nazwisko' jest wymagane.");


        if (!userModel.getRePassword().equals("isEdit")) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
                    "required.password", "Pole 'Hasło' jest wymagane.");
            if (!(userModel.getPassword().equals(userModel.getRePassword()))) {
                errors.rejectValue("password", "notmatch.password");
            }

            if (userModel.getLogin() != null && userService.get(userModel.getLogin()) != null) {
                errors.rejectValue("login", "user.exist");
            }
        }
    }
}
